<?php

namespace plugin\coupon\app\api\service;

use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponGoods;
use plugin\coupon\app\model\CouponReceiveLog;
use support\Db;
use support\spark\exception\ApiException;

class CouponService
{

    /**
     * 获取我的优惠券
     * @param $param
     * @return array
     */
    public function getMyCouponList($param, int $type = 1)
    {
        $couponModel = new Coupon();
        // 一键过期优惠券
        $couponModel->updateByWhere([
            'status' => 3, // 已过期
            'update_time' => now()
        ], [
            ['validity_type', '=', 1],
            ['end_time', '<', now()]
        ]);

        if ($param['status'] == 2) {
            $param['status'] = [2, 3];
        }
        if ($type == 1) {
            $userInfo = getUserInfo();
        } else {
            $userInfo = getUserInfoInPlugin();
        }
        if (empty($userInfo)) {
            throw new ApiException('请先登陆!');
        }
        $couponReceiveLogModel = new CouponReceiveLog();
        $list=$couponReceiveLogModel->getPaginateList([
            ['user_id', '=', $userInfo['id']],
            ['status', 'in', is_array($param['status'])?$param['status']:[$param['status']]]
        ],['code','coupon_id','coupon_name as name','start_time','end_time','status'],['end_time'=>'desc'],[],$param['limit']);
        $couponIds = [];
        foreach ($list['data'] as $vo) {
            $couponIds[] = $vo['coupon_id'];
        }

        $couponModel = new Coupon();
        $couponList = $couponModel->whereIn('id', $couponIds)->with(['couponGoods'])->get()->toArray();

        $couponInfo = [];
        foreach ($couponList as $vo) {
            $couponInfo[$vo['id']] = $vo;
        }
        foreach ($list['data'] as $key => $vo) {
            $info = $couponInfo[$vo['coupon_id']];
            if (!empty($vo['start_time'])) {
                $list['data'][$key]['start_time'] = date('Y-m-d', strtotime($vo['start_time']));
            }
            if (!empty($vo['end_time'])) {
                $list['data'][$key]['end_time'] = date('Y-m-d', strtotime($vo['end_time']));
            }
            $list['data'][$key]['type'] = $info['type'];
            $list['data'][$key]['amount'] = $info['amount'];
            $list['data'][$key]['max_receive_num'] = $info['max_receive_num'];
            $list['data'][$key]['validity_type'] = $info['validity_type'];
            $list['data'][$key]['receive_useful_day'] = $info['receive_useful_day'];
            $list['data'][$key]['is_threshold'] = $info['is_threshold'];
            $list['data'][$key]['threshold_amount'] = $info['threshold_amount'];
            $list['data'][$key]['discount'] = $info['discount'];
        }

        return dataReturn(0, 'success', $list);
    }

    /**
     * 获取可领取的优惠券
     * @param $param
     * @param int $type
     * @return array
     */
    public function getCanReceiveList($param, int $type = 1)
    {
        $couponModel = new Coupon();
        // 一键过期优惠券
        $couponModel->updateByWhere([
            'status' => 3, // 已过期
            'update_time' => now()
        ], [
            ['validity_type', '=', 1],
            ['end_time', '<', now()]
        ]);

        $goodsCouponList = [];
        // 通用券
        $field = ['id','name','type','amount','max_receive_num','validity_type','start_time','end_time','receive_useful_day','is_threshold','threshold_amount','discount'];
        $comCouponList = $couponModel->getAllList(['join_goods' => 1, 'status' => 1], $field);

        // 商品券
        $couponGoodsModel = new CouponGoods();
        $couponGoodsList = $couponGoodsModel->getAllList([
            ['goods_id','in',[$param['goods_id']]]
        ], ['coupon_id']);

        if (!empty($couponGoodsList)) {
            $couponIds = [];
            foreach ($couponGoodsList as $vo) {
                $couponIds[] = $vo['coupon_id'];
            }

            $goodsCouponList = $couponModel->getAllList([
                ['id', 'in', $couponIds],
                ['status', '=', 1]
            ], $field);
        }

        $couponList = array_merge($comCouponList, $goodsCouponList);

        // 用户已经领过的这些券
        $validCouponIds = [];
        foreach ($couponList as $vo) {
            $validCouponIds[] = $vo['id'];
        }

        if ($type == 1) {
            $userInfo = getUserInfo();
        } else {
            $userInfo = getUserInfoInPlugin();
        }
        if (empty($userInfo)) {
            throw  new  ApiException('请先登陆！');
        }

        $userCouponNum = [];
        if (!empty($userInfo)) {
            $couponReceiveLogModel = new CouponReceiveLog();
            $hasReceived = $couponReceiveLogModel->select(['coupon_id',Db::raw('count(*) as c_total')])->where([
                ['coupon_id', 'in', $validCouponIds],
                ['user_id', '=', $userInfo['id']]
            ])->groupBy('coupon_id')->get()->toArray();

            foreach ($hasReceived as $vo) {
                $userCouponNum[$vo['coupon_id']] = $vo['c_total'];
            }
        }

        // 过滤给前端
        foreach ($couponList as $key => $vo) {
            if (!empty($vo['start_time'])) {
                $couponList[$key]['start_time'] = date('Y-m-d', strtotime($vo['start_time']));
            }

            if (!empty($vo['end_time'])) {
                $couponList[$key]['end_time'] = date('Y-m-d', strtotime($vo['end_time']));
            }

            $couponList[$key]['received'] = 0;
            if (!isset($userCouponNum[$vo['id']])) {
                continue;
            }

            $receivedNum = $userCouponNum[$vo['id']];
            if ($receivedNum >= $vo['max_receive_num'] ) {
                $couponList[$key]['received'] = 1;
            }
        }

        return dataReturn(0, 'success', $couponList);
    }



}
